<template>
    <Card style="height: 100%">
        <Button type="primary" style="margin-bottom: 20px" @click="addEnvironment">新建环境</Button>
        <Form ref="FormInline" v-model="searchForm" inline :label-width="80">
            <FormItem label="项目名称">
                <Input v-model="searchForm.name" placeholder="支持模糊匹配"/>
            </FormItem>
            <FormItem label="由我创建">
                <Select placeholder="请选择" v-model="searchForm.member_me" @change="memberChange"
                        style="width: 150px">
                    <Option v-for="item in memberOptionData" :value="item.value" :key="item.value">{{
                        item.name
                        }}
                    </Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="extra">
            <Button type="primary" style="margin-right:8px;" @click="query">查询</Button>
            <Button style="margin-right:8px;" @click="handleReset">重置</Button>
        </div>
        <Table :columns="columns" :data="envData" border :loading="loading">
            <template slot-scope="{ row, index }" slot="action">
                <Button type="primary" size="small" style="margin-right: 5px" @click="handleEdit(row.id)">编辑</Button>
                <Button type="error" size="small" @click="remove(row.id)">删除</Button>
            </template>
        </Table>
        <div style="margin: 10px;overflow: hidden">
            <div style="float: right;">
                <Page :total="total" :current="searchForm.page" :page-size="searchForm.size" @on-change="handleChange"
                      @on-page-size-change="handleSize" show-sizer show-total show-elevator/>
            </div>
        </div>
        <Modal width="45" :value.sync="visible" :title="title">
            <Form ref="environment" :model="environmentForm" :rules="ruleEnvironment" :label-width="80">
                <FormItem label="环境名称" prop="name">
                    <Input v-model="environmentForm.name" placeholder="请输入"/>
                </FormItem>
                <FormItem label="所属项目" prop="project">
                    <Select v-model="edit ? selectedProject : environmentForm.project" placeholder="请选择项目,确认后无法修改"
                            :disabled="disable" @change="projectChange">
                        <Option v-for="item in projectList" :value="item.id" :key="item.id">{{
                            item.name
                            }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="环境地址" prop="base_url">
                    <Input v-model="environmentForm.base_url"
                           placeholder="格式：域名(或IP):端口号，示例：https://www.baidu.com"/>
                </FormItem>
                <FormItem label="环境描述" prop="description">
                    <Input v-model="environmentForm.description" type="textarea" :rows="4" placeholder="请输入"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="cancel">取消</Button>
                <Button type="primary" @click="ok" :loading="addLoading">确定</Button>
            </div>
        </Modal>
    </Card>
</template>

<script>
import {envAdd, envDetail, envDel, envList, projectList, envEdit} from "@/utils/api";

const columns = [
    {
        title: '环境名称',
        key: 'name'
    },
    {
        title: '环境地址',
        key: 'base_url'
    },
    {
        title: '创建人',
        key: 'created_user'
    },
    {
        title: '操作',
        slot: 'action',
        width: 150,
        align: 'center'
    }
]
export default {
    name: "environment_list",
    data() {
        return {
            addLoading: false,
            loading: true,
            columns,
            envData: [],
            total: 0,
            id: 0,
            disable: false,
            edit: false,
            memberOptionData: [{"name": "是", "value": 1}, {"name": "否", "value": 0}],
            searchForm: {
                name: "",
                project: parseInt(localStorage.getItem("project")),
                member_me: 1,
                page: 1,
                size: 10
            },
            selectedProject: [], // 编辑模式下所属项目信息
            environmentForm: {
                name: "",
                base_url: "",
                description: "",
                project: null
            },
            ruleEnvironment: {
                name: [
                    {required: true, message: '环境名称不能为空', trigger: 'blur'}
                ],
                base_url: [
                    {required: true, message: '环境地址不能为空', trigger: 'blur'}
                ],
                project: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (value) {
                                // 验证成功
                                callback();
                            } else {
                                // 验证失败
                                callback(new Error('请选择所属项目'));
                            }
                        },
                        trigger: 'change' // 触发校验的事件
                    }
                ]
            },
            projectList: [], // 项目列表
            visible: false,
            title: "新建环境"
        }
    },
    watch: {
    selectProject(newVal, oldVal) {
        this.searchForm.project = newVal;
      this.query();
    }
  },
  computed: {
    selectProject: {
      get() {
        console.log('1111')
        return this.$store.state.selectProject;
      },
      set(value) {
        console.log('2222')
        this.$store.commit("updateSelectProject", value)
      }
    }
  },
    created() {
        this.query();
        this.getProjectList()
    },
    methods: {
        cancel() {
            this.id = 0;
            this.edit = false;
            this.$refs['environment'].resetFields();
            this.visible = false;
            this.disable = false;
        },
        memberChange(data) {
            this.searchForm.member_me = data
        },
        projectChange(data) {
            this.searchForm.project = data
        },
        handleReset() {
            this.searchForm.name = "";
            this.searchForm.member_me = 1;
            this.searchForm.project = null;
        },
        addEnvironment() {
            this.visible = true;
            this.title = "新增环境";
        },
        handleEdit(id) {
            this.edit = true
            this.id = id;
            this.visible = true;
            this.disable = true;
            this.title = "编辑项目";
            this.addLoading = false;
            this.getEnvironmentDetail(this.id)
        },
        // 获取详情
        getEnvironmentDetail(id) {
            envDetail(id).then(res => {
                this.environmentForm.name = res.data.data.environment.name;
                this.environmentForm.base_url = res.data.data.environment.base_url;
                this.environmentForm.description = res.data.data.environment.description;
                this.selectedProject = res.data.data.environment.project.map(project => project.id)
                this.environmentForm.project = [...this.selectedProject]
            })
        },
        getProjectList() {
            projectList().then(res => {
                this.projectList = res.data.data.projects
            })
        },
        remove(id) {
            this.$Modal.confirm({
                title: "删除提示",
                content: "是否确认删除？",
                okText: "确认",
                cancelText: "取消",
                onOk: async () => {
                    envDel({id: id}).then(res => {
                        if (res.data.result === 1) {
                            this.$Message.success("删除成功!")
                            this.query()
                        } else {
                            this.$Message.error(res.data.error_message)
                            return
                        }
                    })
                }
            })
        },
        close(e) {
            this.id = 0;
            this.edit = false;
            this.visible = e;
        },
        handleChange(e) {
            this.searchForm.page = e;
            this.query();
        },
        handleSize(e) {
            this.searchForm.size = e
            this.query()
        },
        query() {
            this.loading = true;
            envList(this.searchForm).then(res => {
                if (res.data.result === 1) {
                    this.envData = res.data.data.list
                    this.total = res.data.data.total
                    this.loading = false;
                } else {
                    this.loading = false;
                    this.$Message.error("获取环境列表超时!")
                }
            })
        },
        ok() {
            this.$refs['environment'].validate((valid) => {
                if (valid) {
                    this.addLoading = true;
                    if (!this.edit) {
                        const obj = {
                            name: this.environmentForm.name,
                            base_url: this.environmentForm.base_url,
                            project: this.environmentForm.project,
                            description: this.environmentForm.description
                        }
                        envAdd(obj).then(res => {
                            if (res.data.result === 1) {
                                this.$message.success("添加成功!")
                                this.cancel()
                                this.addLoading = false;
                                this.query();
                                return;
                            } else {
                                this.$Message.error(res.data.error_message)
                                this.cancel()
                                this.addLoading = false;
                                return;
                            }
                        })
                    } else {
                        // 编辑操作
                        this.environmentForm.project = this.selectedProject.project;
                        this.environmentForm.id = this.id
                        envEdit(this.environmentForm).then(res => {
                            if (res.data.result === 1) {
                                this.$Message.success("编辑成功")
                                this.addLoading = false;
                                this.disable = false;
                                this.cancel()
                                this.query()
                            }
                        })
                        // envEdit(this.).then(res => {
                        //     if (res.data.errno !== 0) {
                        //         this.$message.error(res.data.errmsg)
                        //         return
                        //     }
                        //     this.$Message.success(res.data.data)
                        //     this.cancel()
                        // })
                    }
                } else {
                    this.visible = true
                }
            })
        },
    }
}
</script>

<style scoped>

</style>
